package com.base.controller.authority;

import com.base.config.Constant;
import com.base.model.LoginModel;
import com.base.model.authority.T_Role;
import com.base.model.authority.T_User;
import com.base.model.authority.T_UserRoles;
import com.base.model.settings.T_Moudle;
import com.jfinal.core.ActionKey;
import com.jfinal.plugin.activerecord.Page;
import com.zh_new.annotation.RouteBind;
import com.zh_new.controller.BaseController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RouteBind(path = "/Main/QxRole", viewPath = "/System/Authority/Role")
public class RoleController extends BaseController {

	public void main() {
		String select = "select id, name, ms, xh, dblimit";
		int pageSize = Constant.PAGE_SIZE;
		int pageNumber = 1;
		try {
			if (null != getPara("numPerPage") && !"".equals(getPara("numPerPage").trim())) {
				pageSize = getParaToInt("numPerPage");
			}
			if (pageSize <= 0) {
				throw new Exception();
			}
			if (null != getPara("pageNum") && !"".equals(getPara("pageNum").trim())) {
				pageNumber = getParaToInt("pageNum");
			}
			if (pageNumber <= 0) {
				throw new Exception();
			}
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的查询参数有误，请检查后重新提交！\"}");
			return;
		}
		String sqlExceptSelect = "from t_role where dbstate='0' order by xh";
		try {
			Page<T_Role> rolePage = T_Role.dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
			setAttr("rolePage", rolePage);
			render("role_main.jsp");
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"服务器存在错误，数据读取失败！\"}");
		}
	}

	/**
	 * 角色信息添加页面
	 */
	public void addip() {
		render("role_add.jsp");
	}

	/**
	 * 角色信息添加处理
	 */
	public void add() {
		int xh;
		if (null == getPara("xh") || 0 == getPara("xh").trim().length()) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		try {
			xh = getParaToInt("xh");
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		if (null == getPara("name") || 0 == getPara("name").trim().length()) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		List<T_Role> roles = T_Role.dao.find("select * from t_role where " + "name='" + getPara("name").trim() + "'");
		if (null != roles && 0 < roles.size()) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，角色名称已经存在！\"}");
			return;
		}
		T_Role role = new T_Role();
		role.set("name", getPara("name").trim()).set("ms", getPara("ms")).set("xh", xh).set("dbstate", "0");
		try {
			if (role.save()) {
				renderJson("{\"statusCode\":\"200\", \"message\":\"角色信息添加完成！\", " + "\"navTabId\":\"rolemg\", \"forwardUrl\":\"\", " + "\"callbackType\":\"closeCurrent\"}");
			} else {
				renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
			}
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
		}
	}

	/**
	 * 角色信息复制页面
	 */
	@ActionKey("/Main/QxRole/addip/copy")
	public void copyip() {
		Integer rId;
		try {
			rId = getParaToInt();
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		T_Role role = T_Role.dao.findById(rId);
		if (null == role) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，角色信息不存在！\"}");
			return;
		}
		setAttr("role", role);
		render("role_copy.jsp");
	}

	/**
	 * 角色信息复制处理
	 */
	@ActionKey("/Main/QxRole/add/copy")
	public void copy() {
		Integer rId;
		try {
			rId = getParaToInt("id");
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		int xh;
		if (null == getPara("xh") || 0 == getPara("xh").trim().length()) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		try {
			xh = getParaToInt("xh");
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		if (null == getPara("name") || 0 == getPara("name").trim().length()) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		T_Role role = T_Role.dao.findById(rId);
		if (null == role) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，复制的角色信息不存在！\"}");
			return;
		}
		List<T_Role> roles = T_Role.dao.find("select * from t_role where " + "name='" + getPara("name").trim() + "'");
		if (null != roles && 0 < roles.size()) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，角色名称已经存在！\"}");
			return;
		}
		T_Role nwerole = new T_Role();
		nwerole.set("name", getPara("name").trim()).set("ms", getPara("ms")).set("xh", xh).set("cmlimit", role.getStr("cmlimit")).set("xtlimit", role.getStr("xtlimit")).set("dbstate", "0");
		try {
			if (nwerole.save()) {
				renderJson("{\"statusCode\":\"200\", \"message\":\"角色信息复制添加完成！\", " + "\"navTabId\":\"rolemg\", \"forwardUrl\":\"\", " + "\"callbackType\":\"closeCurrent\"}");
			} else {
				renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
			}
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
		}
	}

	/**
	 * 角色信息修改页面
	 */
	public void updateip() {
		Integer rId;
		try {
			rId = getParaToInt();
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		T_Role role = T_Role.dao.findById(rId);
		if (null == role) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，角色信息不存在！\"}");
			return;
		}
		setAttr("role", role);
		render("role_update.jsp");
	}

	/**
	 * 角色信息修改处理
	 */
	public void update() {
		Integer rId;
		try {
			rId = getParaToInt("id");
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		int xh;
		if (null == getPara("xh") || 0 == getPara("xh").trim().length()) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		try {
			xh = getParaToInt("xh");
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		if (null == getPara("name") || 0 == getPara("name").trim().length()) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		T_Role role = T_Role.dao.findById(rId);
		if (null == role) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，角色信息不存在！\"}");
			return;
		}
		role.set("ms", getPara("ms")).set("xh", xh);
		if (!role.getStr("name").equals(getPara("name"))) {
			List<T_Role> roles = T_Role.dao.find("select * from t_role where " + "name='" + getPara("name").trim() + "' and id<>" + rId + "");
			if (null != roles && 0 < roles.size()) {
				renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，角色名称已经存在！\"}");
				return;
			}
			role.set("name", getPara("name").trim());
		}
		try {
			if (role.update()) {
				renderJson("{\"statusCode\":\"200\", \"message\":\"角色信息修改完成！\", " + "\"navTabId\":\"rolemg\", \"forwardUrl\":\"\", " + "\"callbackType\":\"closeCurrent\"}");
			} else {
				renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
			}
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
		}
	}

	/**
	 * 角色信息删除处理
	 */
	public void delete() {
		Integer rId;
		try {
			rId = getParaToInt();
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		T_Role role = T_Role.dao.findById(rId);
		if (null == role) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，角色信息不存在！\"}");
			return;
		}
		List<T_UserRoles> userRoles = T_UserRoles.dao.find("select * from t_userroles where r_id=" + rId);
		if (null != userRoles && 0 < userRoles.size()) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"角色信息已经被引用，不能够删除！\"}");
			return;
		}
		try {
			if (role.delete()) {
				renderJson("{\"statusCode\":\"200\", \"message\":\"角色信息删除完成！\", " + "\"navTabId\":\"rolemg\", \"forwardUrl\":\"\"}");
			} else {
				renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
			}
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
		}
	}

	/**
	 * 角色权限分配显示页面
	 */
	public void persetip() {
		Integer rId;
		try {
			rId = getParaToInt();
		} catch (Exception e) {
			toDwzJson(300, "您提交的数据有误，请检查后重新提交！", "", "", "");
			return;
		}
		T_Role role = T_Role.dao.findById(rId);
		if (null == role) {
			toDwzJson(300, "您提交的数据有误，角色信息不存在！", "", "", "");
			return;
		}
		setAttr("role", role);
		String cmlimit = "";
		LoginModel loginModel = (LoginModel) getSessionAttr("loginModel");
		T_User user_op = T_User.dao.findById(loginModel.getUserId());
		List<T_UserRoles> roles = user_op.getRoles();
		if (null == roles || 0 == roles.size()) {
			toDwzJson(300, "您提交的数据有误，用户角色信息不存在！", "", "", "");
			return;
		} else {
			List<String> rcmlimits = new ArrayList<String>();
			for (T_UserRoles userRoles : roles) {
				if (null != userRoles.getRole().getStr("xtlimit")) {
					rcmlimits.add(userRoles.getRole().getStr("xtlimit").trim());
				}
			}
			if (0 == rcmlimits.size()) {
				render("role_perset.jsp");
			} else {
				StringBuffer buffer = new StringBuffer("");
				for (String string : rcmlimits) {
					String[] strings = string.split(",");
					for (int i = 0; i < strings.length; i++) {
						if (buffer.substring(0).indexOf(strings[i] + ",") == -1) {
							buffer.append(strings[i] + ",");
						}
					}
				}
				cmlimit = buffer.substring(0);
			}
		}
		if (cmlimit == null || cmlimit.trim().length() == 0) {
			render("role_perset.jsp");
		} else {
			List<T_Moudle> moudles = new ArrayList<T_Moudle>();
			List<T_Moudle> rootmoudles = T_Moudle.dao.getBaseMoudles();
			if (null != rootmoudles && 0 < rootmoudles.size()) {
				for (T_Moudle moudle : rootmoudles) {
					moudles.add(moudle);
					intoMoudles(moudles, moudle, cmlimit);
				}
				setAttr("moudles", moudles);
			}
			render("role_perset.jsp");
		}

	}

	public void intoMoudles(List<T_Moudle> moudles, T_Moudle moudle, String cmlimit) {
		if (null != moudle.getMoudles() && 0 < moudle.getMoudles().size()) {
			for (T_Moudle smoudle : moudle.getMoudles()) {
				moudles.add(smoudle);
				intoMoudles(moudles, smoudle, cmlimit);
			}
		}
	}

	/**
	 * 角色权限分配处理
	 */
	public void perset() {
		Integer rId;
		try {
			rId = getParaToInt("id");
		} catch (Exception e) {
			toDwzJson(300, "您提交的数据有误，请检查后重新提交！", "", "", "");
			return;
		}
		if (null == getPara("xtlimit")) {
			toDwzJson(300, "您提交的数据有误，未设置拥有权限信息！", "", "", "");
			return;
		}
		T_Role role = T_Role.dao.findById(rId);
		if (null == role) {
			toDwzJson(300, "您提交的数据有误，角色信息不存在！", "", "", "");
			return;
		}

		LoginModel loginModel = (LoginModel) getSessionAttr("loginModel");
		T_User user_op = T_User.dao.findById(loginModel.getUserId());
		List<T_UserRoles> roles = user_op.getRoles();
		if (null == roles || 0 == roles.size()) {
			toDwzJson(300, "您提交的数据有误，用户角色信息不存在！", "", "", "");
			return;
		}

		try {
			if (role.set("xtlimit", getPara("xtlimit").trim()).update()) {
				toDwzJson(200, "角色权限分配完成！", "rolemg", "", "closeCurrent");
			} else {
				toDwzJson(300, "据处理存在错误，权限分配失败！", "", "", "");
			}
		} catch (Exception e) {
			toDwzJson(300, "数据处理存在错误，权限分配失败！", "", "", "");
		}
	}

	public void scheduleip() {
		int id = getParaToInt();
		T_Role role = T_Role.dao.findById(id);
		String dblimit = role.getStr("dblimit");
		Map<Integer, Integer> dbli = new HashMap<Integer, Integer>();
		String[] limits = null;
		if (dblimit != null && dblimit.length() > 0) {
			limits = dblimit.split(",");
			for (String li : limits) {
				if (li.length() > 0)
					dbli.put(Integer.parseInt(li.substring(1)), 1);
			}
		}
		setAttr("dbli", dbli);
		setAttr("role", role);
		render("role_schedule.jsp");
	}

}
